/**
 * @FileName: VerifyPhoneNumberActivity.java
 * @Package:com.bdtop.dbl.ui.activities.acccount
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-15
 * @version V1.0
 */

package com.bdtop.dbl.ui.activities.acccount;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bdtop.dbl.BaseActivity;
import com.bdtop.dbl.R;
import com.bdtop.dbl.server.ServerApiFactory;
import com.bdtop.dbl.server.request.VerifyPhoneNumberRequest.VerifyParams;
import com.bdtop.dbl.server.response.BaseResponse;
import com.bdtop.dbl.thirdparty.asynchttp.RequestCallback;
import com.bdtop.dbl.ui.activities.device.DeviceAddTipActivity;
import com.bdtop.dbl.ui.view.TitleBar;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.NetworkUtils;
import com.bdtop.dbl.utils.Preferences;
import com.bdtop.dbl.utils.SystemUtils;

/**
 * @ClassName: VerifyPhoneNumberActivity
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-15
 */
public class VerifyPhoneNumberActivity extends BaseActivity {

	private static final String PHONE_KEY = "phone_key";

	private TitleBar mTitleBar;

	private TextView mPromptText;
	private EditText mPasswordText;
	private EditText mPwdConfirmText;
	private EditText mVerifyCodeText;
	private Button mReVerifyBtn;
	private Button mOKBtn;

	private String mPhoneNumber;

	private ButtonTimer mButtonTimer;

	public static final void launch(Context context, String phoneNumber) {
		Intent intent = new Intent(context, VerifyPhoneNumberActivity.class);
		intent.putExtra(PHONE_KEY, phoneNumber);

		context.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_verify_phone_number);
		initViews();

		mButtonTimer = new ButtonTimer(60 * 1000, 1000);

		mPhoneNumber = getIntent().getStringExtra(PHONE_KEY);
		mPromptText.setText(getResources().getString(R.string.verify_code_prompt, mPhoneNumber));

		mReVerifyBtn.setEnabled(false);
		if (mButtonTimer != null) {
			mButtonTimer.start();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	private void initViews() {
		mTitleBar = (TitleBar) findViewById(R.id.title_bar);
		mTitleBar.setBelongActivity(this);
		mTitleBar.setTitle(R.string.verify_phone_title);

		mPromptText = (TextView) findViewById(R.id.verify_prompt);

		mPasswordText = (EditText) findViewById(R.id.password);
		mPwdConfirmText = (EditText) findViewById(R.id.password_confirm);
		mVerifyCodeText = (EditText) findViewById(R.id.verify_code);

		mReVerifyBtn = (Button) findViewById(R.id.re_verify_btn);
		mReVerifyBtn.setOnClickListener(mOnClickListener);

		mOKBtn = (Button) findViewById(R.id.ok);
		mOKBtn.setOnClickListener(mOnClickListener);
	}

	private OnClickListener mOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.re_verify_btn:
				mReVerifyBtn.setEnabled(false);
				if (mButtonTimer == null) {
					mButtonTimer = new ButtonTimer(60 * 1000, 1000);
				}
				String phoneNumber = mPhoneNumber;
				ServerApiFactory.getApiImpl().register(phoneNumber, mRegisterCallback);
				break;

			case R.id.ok:
				if (check()) {
					VerifyParams params = new VerifyParams();
					params.setPhoneNumber(mPhoneNumber);
					params.setPassword(mPasswordText.getText().toString());
					params.setVerifyCode(mVerifyCodeText.getText().toString());
					params.setImei(SystemUtils.getImeiCode(VerifyPhoneNumberActivity.this));
					params.setImsi(SystemUtils.getImsiCode(VerifyPhoneNumberActivity.this));

					ServerApiFactory.getApiImpl().verify(params, mVerifyPhoneNumberCallback);
					showWaitingDialog(R.string.waiting_register, false, true);
				}
				break;
			default:
				break;
			}
		}
	};

	private RequestCallback mRegisterCallback = new RequestCallback() {

		@Override
		public void onSuccess(String rawData, Object response) {
			BaseResponse baseResponse = (BaseResponse) response;
			showToast(baseResponse.getDesc());
			if (Constants.REQUEST_SUCCESS.equalsIgnoreCase(baseResponse.getStatus())) {
				mButtonTimer.start();
			}
		}

		@Override
		public void onError(int statusCode, Throwable e, String rawData) {
			if (NetworkUtils.isNetConnect(getApplicationContext())) {
				showToast(R.string.oper_error);
			} else {
				showToast(R.string.net_error);
			}
		}
	};

	private boolean check() {

		if (mPasswordText.getText().toString().trim().length() != mPasswordText.getText().toString().length()) {
			showToast(R.string.pwd_not_has_space);
			return false;
		}

		if (mPasswordText.getText().toString().length() == 0) {
			showToast(R.string.pwd_null);
			return false;
		} else if (mPasswordText.getText().toString().length() < 6) {
			showToast(R.string.pwd_format);
			return false;
		}

		if (mPwdConfirmText.getText().toString().length() == 0) {
			showToast(R.string.re_pwd_null);
			return false;
		} else if (!mPwdConfirmText.getText().toString().equals(mPasswordText.getText().toString())) {
			showToast(R.string.re_pwd_format);
			return false;
		}

		if (mVerifyCodeText.getText().toString().trim().length() == 0) {
			showToast(R.string.code_null);
			return false;
		}

		if (mVerifyCodeText.getText().toString().trim().length() != 4) {
			showToast(R.string.code_format);
			return false;
		}

		return true;
	}

	private RequestCallback mVerifyPhoneNumberCallback = new RequestCallback() {

		@Override
		public void onSuccess(String rawData, Object response) {
			BaseResponse baseResponse = (BaseResponse) response;

			showToast(baseResponse.getDesc());

			if (Constants.REQUEST_SUCCESS.equalsIgnoreCase(baseResponse.getStatus())) {
				// DeviceAddTipActivity.launch(VerifyPhoneNumberActivity.this);
				/** 注册新账户后首次登录直接进入设备添加页面（只有第一次是这样） */
				Preferences.saveRegisterToLogin(getApplicationContext(), true);
				LoginActivity.launch(VerifyPhoneNumberActivity.this);
				

			}
			dismissDialog();
		}

		@Override
		public void onError(int statusCode, Throwable e, String rawData) {
			dismissDialog();
			if (NetworkUtils.isNetConnect(getApplicationContext())) {
				showToast(R.string.oper_error);
			} else {
				showToast(R.string.net_error);
			}
		}
	};

	private class ButtonTimer extends CountDownTimer {

		/**
		 * @param millisInFuture
		 * @param countDownInterval
		 */
		public ButtonTimer(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onFinish() {
			if (mButtonTimer != null) {
				mButtonTimer.cancel();
				mButtonTimer = null;
			}
			mReVerifyBtn.setEnabled(true);
			mReVerifyBtn.setText(R.string.re_verify_phone_number);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			long second = millisUntilFinished / 1000;
			mReVerifyBtn.setText(getResources().getString(R.string.re_verify_phone_number_countdown, second));
		}
	}
}
